import React, { useState, useEffect } from "react";
import "./App.css";
import Login from "./components/Auth/Login";
import Register from "./components/Auth/Register";
import GameStatus from "./components/GameStatus";
import GameActions from "./components/GameActions";
import GameInventory from "./components/GameInventory";
import Adventure from "./components/Adventure/Adventure";
import "./components/styles.css";
import "./components/styles/auth.css";
import type { GameStat, GameActionType, GameItem } from "./types";
import { userAPI, gameAPI, itemAPI } from "./services/api";
import { isAuthenticated, removeAuthToken } from "./services/auth";

function App() {
  // 应用状态
  const [currentView, setCurrentView] = useState<"login" | "register" | "game">(
    "login"
  );
  const [isAuthenticatedUser, setIsAuthenticatedUser] =
    useState<boolean>(false);
  const [userInfo, setUserInfo] = useState<any>(null);

  // 游戏状态管理
  const [gameStarted, setGameStarted] = useState<boolean>(false);
  const [characterName, setCharacterName] = useState<string>("");
  const [gameMessage, setGameMessage] = useState<string>(
    "欢迎来到修仙世界！请输入你的道号开始修炼之旅。"
  );
  const [stats, setStats] = useState<GameStat[]>([
    { label: "境界", value: "练气一层" },
    { label: "灵力", value: "100/100" },
    { label: "法力", value: "50/50" },
    { label: "悟性", value: "10" },
  ]);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [showRegisterSuccess, setShowRegisterSuccess] =
    useState<boolean>(false);
  const [refreshInventory, setRefreshInventory] = useState<number>(0);
  const [showAdventure, setShowAdventure] = useState<boolean>(false);

  // 组件挂载时检查认证状态
  useEffect(() => {
    checkAuthStatus();
  }, []);

  // 检查认证状态
  const checkAuthStatus = async () => {
    if (isAuthenticated()) {
      try {
        const response = await userAPI.getUserInfo();
        if (response.success && response.data) {
          setIsAuthenticatedUser(true);
          setUserInfo(response.data);
          setCharacterName(response.data.nickname || "无名修士");
          setGameMessage(
            `欢迎回来，${response.data.nickname}！继续你的修仙之路吧！`
          );
          setCurrentView("game");
          setGameStarted(true);

          // 初始化游戏状态
          await initializeGame();
        }
      } catch (error) {
        console.error("Failed to get user info:", error);
        removeAuthToken();
      }
    }
  };

  // 登录成功处理
  const handleLoginSuccess = () => {
    checkAuthStatus();
  };

  // 注册成功处理
  const handleRegisterSuccess = () => {
    setShowRegisterSuccess(true);
    setTimeout(() => {
      setShowRegisterSuccess(false);
      setCurrentView("login");
    }, 2000);
  };

  // 初始化游戏状态 - 不再需要显式创建角色
  const initializeGame = async () => {
    setIsLoading(true);
    try {
      // 直接获取游戏状态，而不是创建角色
      const response = await gameAPI.getGameStatus();

      if (response.success && response.data) {
        setGameStarted(true);

        // 更新游戏状态
        const gameData = response.data;
        setStats([
          {
            label: "境界",
            value: `${gameData.realm || "练气期"}${
              gameData.realm_level || 1
            }层`,
          },
          {
            label: "灵力",
            value: `${gameData.hp || 100}/${gameData.hp_max || 100}`,
          },
          {
            label: "法力",
            value: `${gameData.mana || 50}/${gameData.mana_max || 50}`,
          },
          { label: "悟性", value: (gameData.comprehension || 10).toString() },
        ]);
      }
    } catch (error) {
      console.error("Failed to initialize game:", error);
      // 初始化失败时使用默认状态
      setStats([
        { label: "境界", value: "练气一层" },
        { label: "灵力", value: "100/100" },
        { label: "法力", value: "50/50" },
        { label: "悟性", value: "10" },
      ]);
    } finally {
      setIsLoading(false);
    }
  };

  // 请求刷新物品栏
  const requestInventoryRefresh = () => {
    setRefreshInventory((prev) => prev + 1);
  };

  // 游戏动作处理
  const handleAction = async (actionType: GameActionType): Promise<void> => {
    setIsLoading(true);

    try {
      let response: any;
      let message = "";
      let newStats = [...stats];

      switch (actionType) {
        case "meditate":
          // 调用后端API进行打坐修炼
          response = await gameAPI.meditate();
          if (response.success && response.data) {
            message = `${characterName}开始打坐修炼，周围的天地灵气缓缓涌入体内...\n恭喜！你获得了${response.data.cultivation_gained}点修为！`;
            if (response.data.realm_breakthrough) {
              message += `\n恭喜你突破到了${response.data.new_realm}${response.data.new_realm_level}层！`;
              // 更新境界信息
              const realmIndex = newStats.findIndex(
                (stat) => stat.label === "境界"
              );
              if (realmIndex !== -1) {
                newStats[
                  realmIndex
                ].value = `${response.data.new_realm}${response.data.new_realm_level}层`;
                setStats(newStats);
              }
            }
          }
          break;

        case "explore":
          // 调用后端API进行秘境探索
          response = await gameAPI.explore();
          if (response.success && response.data) {
            message =
              response.data.message ||
              `${characterName}探索了秘境，但什么也没有发现。`;
          }
          break;

        case "alchemy":
          // 调用后端API进行炼丹
          response = await gameAPI.alchemy();
          if (response.success && response.data) {
            message =
              response.data.message || `${characterName}尝试炼丹，但失败了。`;
          }
          break;

        case "challengeDemon":
          // 调用后端API挑战心魔
          response = await gameAPI.challengeDemon();
          if (response.success && response.data) {
            message = response.data.message || `${characterName}挑战心魔失败。`;
            if (response.data.success) {
              // 提升悟性
              const perceptionIndex = newStats.findIndex(
                (stat) => stat.label === "悟性"
              );
              if (perceptionIndex !== -1) {
                const currentPerception = parseInt(
                  newStats[perceptionIndex].value
                );
                newStats[perceptionIndex].value = (
                  currentPerception + 1
                ).toString();
                setStats(newStats);
              }
            }
          }
          break;

        default:
          message = "未知的行动";
      }

      setGameMessage(message);

      // 游戏操作后请求刷新物品栏
      requestInventoryRefresh();
    } catch (error) {
      console.error(`执行${actionType}动作失败:`, error);
      setGameMessage("操作失败，请稍后重试。");
    } finally {
      setIsLoading(false);
    }
  };

  // 重新开始游戏
  const restartGame = async (): Promise<void> => {
    // 不再需要设置gameStarted为false，因为我们不再显示游戏开始界面
    setGameMessage(`欢迎回来，${characterName}！准备开始新的修仙之旅吧！`);
    // 调用initializeGame来重置游戏状态
    await initializeGame();
  };

  // 登出
  const handleLogout = () => {
    removeAuthToken();
    setIsAuthenticatedUser(false);
    setUserInfo(null);
    setCurrentView("login");
  };

  return (
    <div className="app-container">
      {/* 登录界面 */}
      {currentView === "login" && (
        <Login
          onLoginSuccess={handleLoginSuccess}
          onGoToRegister={() => setCurrentView("register")}
        />
      )}

      {/* 注册界面 */}
      {currentView === "register" && (
        <Register
          onRegisterSuccess={handleRegisterSuccess}
          onGoToLogin={() => setCurrentView("login")}
        />
      )}

      {/* 注册成功提示 */}
      {showRegisterSuccess && (
        <div className="success-overlay">
          <div className="success-message">
            <h3>注册成功！</h3>
            <p>即将跳转到登录页面...</p>
          </div>
        </div>
      )}

      {/* 游戏界面 */}
      {currentView === "game" && isAuthenticatedUser && (
        <>
          <header className="game-header">
            <div className="header-content">
              <div>
                <h1>一念之间 - 修仙游戏</h1>
                <p>修仙之路，一念成圣，一念成魔</p>
              </div>
              <button className="logout-button" onClick={handleLogout}>
                登出
              </button>
            </div>
          </header>

          <main className="game-main">
            <div className="game-screen">
              <GameStatus
                characterName={characterName}
                stats={stats}
                gameMessage={gameMessage}
              />

              <GameActions onAction={handleAction} isLoading={isLoading} />

              <GameInventory key={refreshInventory} />

              <div className="game-controls">
                <button
                  className="adventure-button"
                  onClick={() => setShowAdventure(true)}
                  disabled={isLoading}
                  style={{
                    background:
                      "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
                    color: "white",
                    padding: "12px 24px",
                    fontSize: "16px",
                    fontWeight: "bold",
                    border: "none",
                    borderRadius: "8px",
                    cursor: "pointer",
                    marginRight: "10px",
                    boxShadow: "0 4px 15px rgba(102, 126, 234, 0.3)",
                    transition: "all 0.3s ease",
                  }}
                >
                  🗡️ 开始历练
                </button>
                <button
                  className="restart-button"
                  onClick={restartGame}
                  disabled={isLoading}
                >
                  重新开始
                </button>
              </div>
            </div>
          </main>

          <footer className="game-footer">
            <p>一念之间 © 2025 修仙模拟器</p>
          </footer>

          {/* 历练模态框 */}
          {showAdventure && (
            <Adventure
              characterName={characterName}
              stats={stats}
              onClose={() => setShowAdventure(false)}
            />
          )}
        </>
      )}
    </div>
  );
}

export default App;
